<?php
#####################################################
# RWCARDS - Joomla E-Cards Componment!
# Copyright (C) 2004/2005 by Ralf Weber
# Company    : LoadBrain
# Homepage   : www.weberr.de
# Version    : 2.1.0
# Date       : 23/11/2005
# License    : Released under GPL
######################################################
session_start();

defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

$task = trim( mosGetParam( $_REQUEST, 'task', "" ) );
$cardId = intval( mosGetParam( $_REQUEST, 'cardId', 0 ) );
$sesja = trim( mosGetParam( $_REQUEST, 'sesja', "" ) );
$imieod = trim( mosGetParam( $_REQUEST, 'imieod', "" ) );
$emailod = trim( mosGetParam( $_REQUEST, 'emailod', "" ) );
$sesjaID = trim( mosGetParam( $_REQUEST, 'sesjaID', "" ) );
/*echo $_REQUEST['sesja']; exit;
( !isset($sesja) ) ? $sesja = "" : "";
( !isset($imieod) ) ? $imieod = "" : "";
( !isset($emailod) ) ? $emailod = "" : "";
( !isset($sesjaID) ) ? $sesjaID = "" : "";
*/

require_once( $mainframe->getPath( 'front_html' ) );
require_once( $mainframe->getPath( 'class' ) );


require_once './components/com_rwcards/Pager/Pager.php';
require_once './components/com_rwcards/captcha/class.captcha.php';

if (!defined( '_RWCARDS_LANG_INCLUDED' )) 
{
    if (file_exists("./components/com_rwcards/language/" . $mosConfig_lang . ".php") ) 
       {
           include_once("./components/com_rwcards/language/" . $mosConfig_lang . ".php");
    }
       else
       {
        include_once("./components/com_rwcards/language/english.php");
    }
}

// Standard (D)HTML...
echo ("<div id=\"overDiv\" style=\"position:absolute; visibility:hidden; z-index:1000;\"></div>\n"
 . "\t<script language=\"JavaScript\" src=\"" . $mosConfig_live_site . "/includes/js/overlib_mini.js\"></script>\n");

switch($task)
{
   case "ViewCard":
          ViewCard($_REQUEST['id'], $_REQUEST['Itemid'], $_REQUEST['sessionId']);

          break;
   case "FillCard":
          FillCard($cardId, $Itemid, $sesjaID, $imieod, $emailod);
          break;
   case "SendCard":
		if ($_REQUEST['submit'] == _PREVIEW_CARD)
		{
				PreviewCard( $cardId, $Itemid);
		}
		else
		{
				SendCard( $cardId, $Itemid);
		}
			break;
   case "listCards":
	        ListCards($Itemid, $sesja);
          break;
	 default:
		      firstView($Itemid, $sesja);
          break;
}



/**
* checkCapture
* @param string cardId
* @param string Itemid
* @version 2.2
*
*/
function checkCapture($cardId, $Itemid)
{
	global $database, $mosConfig_live_site;
	
  	//captcha
	if ($_REQUEST['captcha_config'] == "1")
	{
	 	 if (empty($_GET['session_code'])) 
	 	 { 
	 	 	 $session_code = md5(round(rand(0,40000))); 
		 } 
		 else 
		 { 
		 	 $session_code=$_GET['session_code']; 
		 }	
	
  	$my_captcha = new captcha( $session_code, './components/com_rwcards/captcha/__TEMP__' ); 
  	
  	$do = $_GET['do'];
  	
  	if ($do == 'verify')
  	{
  	if ($my_captcha->verify( $_POST['rwCardsForm']['captcha'] ) )
  		{
				if ($_REQUEST['submit'] == _PREVIEW_CARD)
				{
  				PreviewCard( $cardId, $Itemid);
				}
				else
				{
  				SendCard( $cardId, $Itemid);
				}
  		}
  		else
  		{
			 
			 //mosredirect("index.php?option=" . $_REQUEST['option'] . "&Itemid=" . $_REQUEST['Itemid'] . "&task=FillCard&cardId=" . $cardId . "'");
  		 echo "<script language=\"JavaScript\" type=\"text/javascript\">\n";
			 echo "<!--\n";
			 echo "alert('" . _RWCARDS_FORM_CAPTURE_ERROR_MESSAGE . "');\n";
			 echo "location.href = 'index.php?option=" . $_REQUEST['option'] . "&Itemid=" . $_REQUEST['Itemid'] . "&task=FillCard&cardId=" . $cardId . "&sesjaID=" . $_REQUEST['sesjaID'] . "'";
			 echo "//-->\n";
			 echo "</script>\n";
			 exit;
  		}
		}
	}
	// no CAPTCHA activated
	else
	{
    if ($_REQUEST['submit'] == _PREVIEW_CARD)
    {
     PreviewCard( $cardId, $Itemid);
    }
    else
    {
     SendCard( $cardId, $Itemid);
    }
	}
}
/**
* SendCard
* @param string cardId
* @param string Itemid
* @version 2.0
*
*/
function SendCard($cardId, $Itemid)
{	
	global $database, $mosConfig_live_site;
	
	$cardId = RWCardsCleanInput($cardId);
	$nameTo = RWCardsCleanInput($_REQUEST['rwCardsForm']['nameTo']);
	$nameFrom = RWCardsCleanInput($_REQUEST['rwCardsForm']['nameFrom']);
	$message = RWCardsCleanInput($_REQUEST['rwCardsForm']['message']);
	$emailTo = RWCardsCleanInput($_REQUEST['rwCardsForm']['emailTo']);
	$emailFrom = RWCardsCleanInput($_REQUEST['rwCardsForm']['emailFrom']);	   
	$sendDate = RWCardsCleanInput($_REQUEST['rwCardsForm']['sendDate']);	   

	// check the config settings
	$database->setQuery("SELECT attachement FROM #__rwcardsconfig");
	$attachement = $database->loadResult();
	
	$database->setQuery("SELECT picture FROM #__rwcards where id = '" . $cardId . "'");
	$picture = $database->loadResult();
	
	$database->setQuery("INSERT INTO #__rwcardsdata SET picture= '" . $picture . "', nameTo = '" .$nameTo . "', nameFrom = '" . $nameFrom . "', emailTo = '" .$emailTo . "', emailFrom = '" .$emailFrom . "', message = '" .$message . "', sessionID = '" . $_REQUEST["PHPSESSID"] . "' , writtenOn = '" . date("Y-m-d") . "', sendDate = '" . $sendDate . "'");
	$database->query();
	$lastId = $database->insertid();
	$ToSubject = _SUBJECT . $nameFrom;
	$link = $mosConfig_live_site."/index.php?option=com_rwcards&Itemid=" . $Itemid . "&sessionId=" . $_REQUEST["PHPSESSID"] . "&id=" . $lastId . "&task=ViewCard&read=1&sendmail=1";
	$linkToViewOnly = $mosConfig_live_site."/index.php?option=com_rwcards&Itemid=" . $Itemid . "&sessionId=" . $_REQUEST["PHPSESSID"] . "&id=" . $lastId . "&task=ViewCard&sendmail=0";
	
	if ($sendDate == date("Y-m-d"))
	{
		/**
		* Mail function (uses phpMailer)
		* @param string From e-mail address
		* @param string From name
		* @param string/array Recipient e-mail address(es)
		* @param string E-mail subject
		* @param string Message body
		* @param boolean false = plain text, true = HTML
		* @param string/array CC e-mail address(es)
		* @param string/array BCC e-mail address(es)
		* @param string/array Attachment file name(s)
		* mosMail($from, $fromname, $recipient, $subject, $body, $mode=0, $cc=NULL, $bcc=NULL, $attachment=NULL )	
		*/
	
		// send link to card
		if ($attachement == "0")
		{
			$toMessage = _GREETING . $nameTo . "\n" . $nameFrom . _MSG_PART_1 . $link . _MSG_COPYRIGHT;
			mosMail($emailFrom, $nameFrom, $emailTo, $ToSubject, $toMessage);
		}
		// send card as attachement
		else
		{
			$toMessage = _GREETING . $nameTo . "\n" . $nameFrom . _MSG_ATTACHEMENT_1 . $message . _MSG_COPYRIGHT;
			mosMail($emailFrom, $nameFrom, $emailTo, $ToSubject, $toMessage, 0,  $cc=NULL, $bcc=NULL, "./images/stories/cards/" . $picture);
		}
		$database->setQuery("UPDATE #__rwcardsdata SET cardSent = '1' where id = '" . $lastId . "' and sessionId = '" . $_REQUEST["PHPSESSID"] . "'");
		$database->query();
		$step = _CARD_SENT;
	}
	else
	{
		$step = _CARD_SEND_ADVANCED;
	}
	rwcards_html::setTitle($step);
	rwcards_html::CardSent($linkToViewOnly, $sendDate);
	rwcards_html::RWCardsWriteFooter();
	@session_destroy();
}

/**
* PreviewCard
* @param string cardId
* @param string Itemid
* @version 2.0
*
*/
function PreviewCard($cardId, $Itemid)
{
	global $database, $mosConfig_live_site;

	$cardId = RWCardsCleanInput($cardId);
	$nameTo = RWCardsCleanInput($_REQUEST['rwCardsForm']['nameTo']);
	$nameFrom = RWCardsCleanInput($_REQUEST['rwCardsForm']['nameFrom']);
	$message = RWCardsCleanInput($_REQUEST['rwCardsForm']['message']);
	$emailTo = RWCardsCleanInput($_REQUEST['rwCardsForm']['emailTo']);
	$emailFrom = RWCardsCleanInput($_REQUEST['rwCardsForm']['emailFrom']);
	$sendDate = RWCardsCleanInput($_REQUEST['rwCardsForm']['sendDate']);	
	$image = $_REQUEST['rwCardsForm']['image'];
					 
	$_SESSION['nameFrom'] = $nameFrom;
	$_SESSION['emailFrom'] = $emailFrom;
	$_SESSION['nameTo'] = $nameTo;
	$_SESSION['emailTo']= $emailTo;
	$_SESSION['message'] = $message;
	$_SESSION['sendDate'] = $sendDate;
	$_SESSION['image'] = $image;

	if (eregi( "\.jpg", $image ))
	{
		$database->setQuery("SELECT autor, description FROM #__rwcards where picture = '" . strtolower( substr($image, 0, -6) ) . ".jpg" . "'");
	}
	else
	{
		$database->setQuery("SELECT autor, description FROM #__rwcards where picture = '" . $image . "'");
	}
	$rows = $database->loadObjectList();

       
	$info =  _RWCARDS_AUTHOR . @$rows[0]->autor . "<br>" . _RWCARDS_DESCRIPTION . @$rows[0]->description;
	
	//bgcolor
	$database->setQuery("SELECT  backgroundcolor FROM #__rwcardsconfig");
    $bgcolor = $database->loadObjectList();
	
	$step = _RWCARDS_LANG_PREVIEW;

	rwcards_html::setTitle($step);
	rwcards_html::RWCardsPreviewSentCard($cardId, $Itemid, $image, nl2br($message), $info, $bgcolor);
	rwcards_html::RWCardsWriteFooter();
}

/**
* FillCard
* @param int id
* @param string Itemid
* @param string sesjaID
* @version 2.0
*
*/
function FillCard($id, $Itemid, $sesjaID)
{
	global $database, $mosConfig_live_site, $my;
	// if user logged in, get name & email for fields in card
	if($my->id)
	{
		$database->setQuery("SELECT  username, email FROM #__users where id = '" . $my->id . "'");
		$userdata = $database->loadObjectList();
	}
	$database->setQuery("SELECT  maxadvanced, captcha FROM #__rwcardsconfig");
	$advanceddays = $database->loadObjectList();
	$captcha = $advanceddays[0]->captcha;
	$advanceddays = $advanceddays[0]->maxadvanced;
	$step = _RWCARDS_LANG_STEP2;
	$rows = "";
	
	if( $sesjaID !="")
	{
		$database->setQuery("SELECT nameFrom, emailFrom FROM #__rwcardsdata where sessionId  = '" . $sesjaID . "'");
    	$rows = $database->loadObjectList();
	}

	$database->setQuery("SELECT picture FROM #__rwcards where id = '" . $id . "'");
	$image = $database->loadResult();
	rwcards_html::setTitle($step);
	rwcards_html::RWCardsWriteForm($id, $Itemid, $image, $rows, $sesjaID, $advanceddays, $captcha, $userdata);
	rwcards_html::RWCardsWriteFooter();
}

/**
* ViewCard
* @param int id
* @param string Itemid
* @param string sesjaID
* @version 2.0
*
*/
function ViewCard($id, $Itemid, $sessionId)
{
	global $database;
	
	$step = _STEP_VIEW;
	
	$database->setQuery("SELECT * FROM #__rwcardsdata where id = '" . $id . "' and sessionId = '" . $sessionId . "'");
	$res = $database->loadObjectList();
	
	$database->setQuery("SELECT autor, description FROM #__rwcards where picture = '" . $res[0]->picture . "'");
    $rows = $database->loadObjectList();
	$info =  _RWCARDS_AUTHOR . $rows[0]->autor . "<br>" . _RWCARDS_DESCRIPTION . $rows[0]->description;
	
	// first time card is viewed, send an email to sender
	if( ($res[0]->cardRead == '0') && ($_REQUEST['sendmail'] == '1') )
	{
		// email for info that card was read to sender
		/**
		* Mail function (uses phpMailer)
		* @param string From e-mail address
		* @param string From name
		* @param string/array Recipient e-mail address(es)
		* @param string E-mail subject
		* @param string Message body
		* @param boolean false = plain text, true = HTML
		* @param string/array CC e-mail address(es)
		* @param string/array BCC e-mail address(es)
		* @param string/array Attachment file name(s)
		* mosMail($from, $fromname, $recipient, $subject, $body, $mode=0, $cc=NULL, $bcc=NULL, $attachment=NULL )	
		*/                          
		$body =  _GREETING . $res[0]->nameFrom . "\n\n" . $res[0]->nameTo . _CARD_READ_MSG_1 . date(" d.m.Y, H:i:s ") .   _CARD_READ_MSG_2 . _MSG_COPYRIGHT;
		mosMail($res[0]->emailFrom, $res[0]->nameFrom, $res[0]->emailFrom, _CARD_READ_SUBJECT, $body);
	}
	// update state of card to read
	if( isset($_GET['read']) && $_GET['read'] == "1" )
    {
		// gelesen auf 1 setzen 
		$database->setQuery("UPDATE #__rwcardsdata SET cardRead = '1' where id = '" . $id . "' and sessionId = '" . $sessionId . "'");
		$database->query();
    }

	// bgcolor
	$database->setQuery("SELECT  backgroundcolor FROM #__rwcardsconfig");
    $bgcolor = $database->loadObjectList();

	rwcards_html::setTitle($step);
	rwcards_html::RWCardsWrite($res, $info, $Itemid, $sessionId, $bgcolor);
	rwcards_html::RWCardsWriteFooter();
}


/**
* firstView
* @param string Itemid
* @param string sesjaID
* @version 2.0
*
* First impression of RWCards, view all categories with one picture  as example
*/
function firstView($Itemid, $sesja)
{
       global $database;

       $database->setQuery("SELECT * FROM #__rwcards, #__rwcards_category where category_id = #__rwcards_category.id and #__rwcards.published  = '1' and #__rwcards_category.published = '1' order by #__rwcards_category.ordering, #__rwcards.ordering");
       $cards = $database->loadObjectList();
			 
       $step = _RWCARDS_LANG_STEP1;
       rwcards_html::RWCardsFirstView($cards, $Itemid, $sesja);
       rwcards_html::RWCardsWriteFooter();
}

/**
* ListCards
* @param string Itemid
* @param string sesjaID
* @version 2.0
*
*/
function ListCards($Itemid, $sesja)
{
       global $database;
       
	   // lifetime
       $database->setQuery("SELECT * FROM #__rwcardsconfig");
       $conf = $database->loadObjectList();
       // categories
       $database->setQuery("SELECT * FROM #__rwcards_category where published >= 0 order by ordering");
       $res = $database->loadObjectList();

       // is a category choosed
       if ( isset($_REQUEST["category_id"]) )
       {
              foreach ($res as $key => $val)
              {
                     if ($val->id == $_REQUEST["category_id"])
                     {
                            $selectedCategory = $val->category_kategorien_name ;
                            $selectedCategoryId = $val->id;
                     }
                     $categories[] = mosHTML::makeOption($val->id, $val->category_kategorien_name);
              }
              $categoryList = mosHTML::selectList( $categories, 'category_id', "class=\"inputbox\" size=\"1\", onchange=\"changeCategory();\"", 'value', 'text', $selectedCategoryId);
              $category = $database->loadObjectList();
			  $database->setQuery("SELECT * FROM #__rwcards where category_id  = '" . $_REQUEST["category_id"] . "' and published  = '1' order by #__rwcards.ordering");
       }
       else
       {
	   		  $_REQUEST["category_id"] = $res[0]->id;
              foreach ($res as $key => $val)
              {
                     $categories[] = mosHTML::makeOption($val->id, $val->category_kategorien_name);
              }
              $categoryList = mosHTML::selectList( $categories, 'category_id', "class=\"inputbox\" size=\"1\", onchange=\"changeCategory();\"", 'value', 'text', $selectedCategoryId);
              $category = $database->loadObjectList();
              $selectedCategory = $category[0]->category_kategorien_name;
              $database->setQuery("SELECT * FROM #__rwcards where category_id  = '" . $res[0]->id . "' and published  = '1' order by #__rwcards.ordering");
       }
       $cards = $database->loadObjectList();
       $step = _RWCARDS_LANG_STEP1;
       rwcards_html::RWCardsListCards($step, $cards, $Itemid, $selectedCategory, $categoryList, $sesja, $conf);
       rwcards_html::RWCardsWriteFooter();
}

/**
* RWCardsCleanInput
* @param string text
* @version 2.0
*
*/
function RWCardsCleanInput($text)
{
	$text = strip_tags($text);
	$text = str_replace("&","and",$text);
	$badChars = array('<', '>', '\\', '/', '=','"',';');
	$text = str_replace($badChars, "", $text);
	$text = str_replace("'", "\'", $text);
	return $text;
}
?>
